package com.xzjt.service.impl;

import cn.hutool.json.JSONObject;
import com.xzjt.entity.SysUser;
import com.xzjt.service.LoginService;
import com.xzjt.utils.JSONUtils;
import com.xzjt.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: LoginServiceImpl
 * @Author: yuandong
 * @Date 2021/10/9 15:52
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public String createToken(SysUser user) {
        long tokenExpireTime = 60;//登录有效期
        String token= JwtUtil.generate(user.getUsername());
        JSONObject obj = new JSONObject();
        obj.put("user", user);
        // 将token放入缓存
        if (tokenExpireTime < 0) {
            stringRedisTemplate.opsForValue().set(token, JSONUtils.toJsonStr(obj));
        } else {
            stringRedisTemplate.opsForValue().set(token, JSONUtils.toJsonStr(obj), tokenExpireTime, TimeUnit.MINUTES);
        }
        return token;
    }
}
